package org.example.xls.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.example.xls.mapper.LoginMapper;
import org.example.xls.pojo.User;
import org.example.xls.service.LoginService;
import org.example.xls.tool.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Value("${wx.secret}")
    String secret;
    @Value("${wx.appid}")
    String appid;
    @Autowired
    private LoginMapper loginMapper;
    @Override
    @Transactional
    public User login(String code) {
        String url="https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
        RestTemplate restTemplate=new RestTemplate();
        String result=restTemplate.getForObject(url,String.class);
        ObjectMapper objectMapper=new ObjectMapper();
        try {
            Map<String,Object> map=objectMapper.readValue(result,Map.class);
            String openid=(String) map.get("openid");

            log.info("openid: {}",openid);
            //生成jwt令牌

            HashMap<String, Object> claims = new HashMap<>();
            claims.put("openid",openid);
            String token=JwtUtil.createJWT(claims);
            User user=loginMapper.getUserByOpenid(openid);
            if(user==null){
                loginMapper.insertUserByOpenid(openid);
                user= loginMapper.getUserByOpenid(openid);
            }

            //将token封装到User中
            user.setToken(token);
            log.info("{}",user);
            return user;
        } catch (Exception e) {
            log.error("Error occurred while generating token: ", e);
        }
        return new User();
    }
}